<?php

namespace apiend\modules\mall\models;

use Yii;
use yii\db\Exception;
use common\models\shop\ShopOrder;
use common\models\shop\ShopOrderExtras;

/**
 * 定制服务模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class OrderExtrasForm extends \common\base\Model {

    /**
     * @var integer 下单用户ID
     */
    public $user_id;

    /**
     * @var integer 订单ID
     */
    public $order_id;

    /**
     * @var string 商品ID
     */
    public $product_id;

    /**
     * @var string 价格
     */
    public $price;

    /**
     * @var string 描述
     */
    public $description;

    /**
     * @var ShopOrder|null 定制订单
     */
    private $_model = null;

    /**
     * 请求参数校验
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id', 'order_id', 'product_id', 'price'], 'required'],
            ['price', 'number'],
            ['price', 'compare', 'compareValue' => 0, 'operator' => '>='],
            ['description', 'string', 'max' => 255],
            ['order_id', 'validateOrder'],
        ];
    }

    /**
     * 校验购物车中的商品
     * @param string $attribute the attribute currently being validated
     */
    public function validateOrder($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = ShopOrder::find()->active()->andWhere([
            'and',
            ['id' => $this->$attribute],
            [
                'status' => [
                    ShopOrder::STATUS_DEFAULT,
                    ShopOrder::STATUS_ACTIVE,
                ]
            ],
        ])->one();
        if (!$model) {
            return $this->addError($attribute, '订单信息不存在或者状态已变更');
        }
        if ($model->isExpired) {
            return $this->addError($attribute, '订单已过期');
        }
        $this->_model = $model;
    }

    /**
     * 获取订单数据
     * @return ShopOrder|null
     */
    protected function getModel() {
        return $this->_model;
    }

    /**
     * 订单下单保存
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('服务内容保存失败');
        }

        $model = ShopOrderExtras::findOrNew([
            'order_id' => $this->order_id,
            'product_id' => $this->product_id,
        ]);
        $model->price = $this->price;
        $model->name = $this->description;

        $order = $this->getModel();
        $oldAmount = $order->amount - $order->extras;

        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception('定制费用保存失败！');
            }
            $extras = ShopOrderExtras::find()->andWhere(['order_id' => $order->id])->sum('price');
            $order->extras = $extras;
            $order->amount = $oldAmount + $extras;
            if (!$order->save()) {
                throw new Exception('订单更新失败！');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        return OrderView::findOne($order->id);
    }

}
